<script setup lang="ts">
import {
  NTabs,
  NTabPane,
  NCard,
  NForm,
  NFormItemRow,
  NButton,
  NInput,
  useMessage,
} from "naive-ui";
import { ref } from "vue";
import { useRouter } from "vue-router";
import { login, register } from "../apis/user";
import { useUserStore } from "../stores/userStore";
const userStore = useUserStore();
const router = useRouter();
const message = useMessage();
const toHome = () => {
  router.push({ path: "/" });
};
const username = ref<string>("");
const pwd = ref<string>("");
const pwd2 = ref<string>("");
const loginOL = async () => {
  const res = await login(username.value, pwd.value);
  if (res.status === 200) {
    message.success(res.data.message);
    userStore.setUserId(res.data.user_id);
    userStore.setPoints(res.data.points);
    userStore.setUserName(username.value);
    message.error("Invalid credentials");
    toHome();
  } else {
    message.error(res.data.error);
  }
};
const registerOL = async () => {
  const res = await register(username.value, pwd.value);
  console.log(res);
  if (res.status === 201) {
    message.success(res.data.message);
  } else {
    message.error(res.data.error);
  }
};
</script>
<template>
  <n-card style="max-width: 500px; min-width: 400px; margin: 0 auto">
    <n-tabs
      class="card-tabs"
      default-value="signin"
      size="large"
      animated
      pane-wrapper-style="margin: 0 -4px"
      pane-style="padding-left: 4px; padding-right: 4px; box-sizing: border-box;"
    >
      <n-tab-pane name="signin" tab="登录">
        <n-form>
          <n-form-item-row label="用户名">
            <n-input v-model:value="username" />
          </n-form-item-row>
          <n-form-item-row label="密码">
            <n-input
              v-model:value="pwd"
              type="password"
              show-password-on="mousedown"
            />
          </n-form-item-row>
        </n-form>
        <n-button type="primary" block secondary strong @click="loginOL">
          登录
        </n-button>
      </n-tab-pane>
      <n-tab-pane name="signup" tab="注册">
        <n-form>
          <n-form-item-row label="用户名">
            <n-input v-model:value="username" />
          </n-form-item-row>
          <n-form-item-row label="密码">
            <n-input
              v-model:value="pwd"
              type="password"
              show-password-on="mousedown"
            />
          </n-form-item-row>
          <n-form-item-row label="重复密码">
            <n-input
              v-model:value="pwd2"
              type="password"
              show-password-on="mousedown"
            />
          </n-form-item-row>
        </n-form>
        <n-button type="primary" block secondary strong @click="registerOL">
          注册
        </n-button>
      </n-tab-pane>
    </n-tabs>
  </n-card>
</template>
